import { uuidv4 } from '@/utils/uuidv4'
import { nextTick } from 'vue'
import iconList from '@/common/IconList'
import { xor } from 'lodash'

function useCesium() {
    let viewer: Cesium.Viewer

    let entityDataSource: Cesium.CustomDataSource

    function setViewer(out_viewer: Cesium.Viewer) {
        viewer = out_viewer
    }

    function setEntityDataSource(out_ds: Cesium.CustomDataSource) {
        entityDataSource = out_ds
    }

    function addCesiumLocalTile(viewer: Cesium.Viewer) {
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0))

        const layer = new Cesium.UrlTemplateImageryProvider({
            // url: '/tiles/img_c/{oz}/{x}/{y}',
            url: '/download/tiles/googletile/{oz}/{x}/{y}.png',
            customTags: {
                oz(imageProvider: any, x: number, y: number, level: number) {
                    return level
                },
            },
            // tileHeight: 256,
            // tileWidth: 256,
            // tilingScheme: new Cesium.GeographicTilingScheme({}),
        })
        viewer.imageryLayers.addImageryProvider(layer)
    }

    function addCesiumLocalLabelTile(viewer: Cesium.Viewer) {
        const layer = new Cesium.UrlTemplateImageryProvider({
            url: '/tiles/label/{oz}/{x}/{y}',
            customTags: {
                oz(imageProvider: any, x: number, y: number, level: number) {
                    return level + 1
                },
            },
            tileHeight: 256,
            tileWidth: 256,
            tilingScheme: new Cesium.GeographicTilingScheme({}),
        })
        viewer.imageryLayers.addImageryProvider(layer)
    }

    function flyToPos(
        viewer: Cesium.Viewer,
        pos: {
            lng: number
            lat: number
            height: number
        },
    ) {
        viewer.scene.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
                pos.lng,
                pos.lat,
                pos.height ?? 100000000,
            ),
            orientation: {
                heading: Cesium.Math.toRadians(180),
                pitch: Cesium.Math.toRadians(-30),
                roll: 0,
            },
            duration: 1000,
            complete: function () {
                console.log('complete')
            },
        })
    }

    function lookAtModel(viewer: Cesium.Viewer, entity: Cesium.Entity) {
        viewer.selectedEntity = entity
    }

    function createModel(url: string, x: number, y: number, height?: number) {
        const position = Cesium.Cartesian3.fromDegrees(
            x,
            y,
            height ?? 100000000,
        )
        return viewer.entities.add({
            name: url,
            position: position,
            model: {
                uri: url,
            },
        })
    }

    function load3DModel(viewer: Cesium.Viewer) {
        const url_plane = '/models/CesiumAir/Cesium_Air.glb'
        const url_ballon = '/models/CesiumBalloon/CesiumBalloon.glb'
        const url3 = '../SampleData/models/CesiumBalloon/CesiumBalloon.glb'
        const entity_plane = createModel(url_plane, 120, 60, 1000)
        const entity_ballon = createModel(url_ballon, 120, 60, 1000)

        viewer.trackedEntity = entity_plane
    }

    type ColorEnum = 'RED' | 'GREEN' | 'BLUE' | 'YELLOW' | 'GRAY'
    function getColor(colorName: ColorEnum, alpha: number) {
        const color = Cesium.Color[colorName]
        return Cesium.Color.fromAlpha(color, alpha)
    }

    function useModelDiffDemo() {
        const url_plane = '/models/CesiumAir/Cesium_Air.glb'
        const url_ballon = '/models/CesiumBalloon/CesiumBalloon.glb'

        const entity_plane = new Cesium.Entity({
            position: Cesium.Cartesian3.fromDegrees(120, 60, 1000),
            model: {
                uri: url_plane,
                color: getColor('RED', 0.5),
            },
        })
        viewer.entities.add(entity_plane)
        viewer.trackedEntity = entity_plane

        const model_ballon = new Cesium.ModelGraphics({
            uri: url_ballon,
            color: getColor('GREEN', 0.5),
        })

        const entity_ballon = new Cesium.Entity({
            position: Cesium.Cartesian3.fromDegrees(120, 60, 1000),
            model: model_ballon,
        })

        // entity_ballon.model
        viewer.entities.add(entity_ballon)
        viewer.trackedEntity = entity_ballon
    }

    // function compareModel(model_a:Cesium.Model,model_b:Cesium.Model){
    //     const addedPrimitive = model1.getMesh('mesh').primitives[0].clone();
    //     const removedPrimitive = model1.getMesh('mesh').primitives[0].clone();

    // }

    function addPrimitiveDemo() {
        const url_plane = '/models/CesiumAir/Cesium_Air.glb'
        const url_ballon = '/models/CesiumBalloon/CesiumBalloon.glb'
        const url_box = '/models/BoxInstanced/BoxInstanced.gltf'

        const planeModelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
            Cesium.Cartesian3.fromDegrees(120, 60, 1000),
        )

        let m = Cesium.Model.fromGltf({
            url: url_plane,
            modelMatrix: planeModelMatrix,
        })

        // Cesium.Model.fromGltf({
        //     url: url_box,
        //     modelMatrix: planeModelMatrix,
        // }).getMesh()

        let planeModel = viewer.scene.primitives.add(m)
        console.log('planeModel======>', planeModel)

        let node = planeModel.getNode('node')

        

        // mesh.material = Cesium.Color.RED.withAlpha(0.5)
        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(120, 60, 1000),
            // orientation: {
            //     heading: Cesium.Math.toRadians(180),
            //     pitch: Cesium.Math.toRadians(-30),
            //     roll: 0,
            // },
            // duration: 1000,
            // complete: function () {
            //     console.log('complete')
            // },
        })
    }

    // 处理第二个网格中新增的三角形

    function useDynamicArea() { }
    function useDynamicPath() { }

    function initCesium(element?: HTMLElement) {
        if (!globalThis.Cesium) {
            console.warn('Cesium load unsuccess')
            return
        }

        if (!element) {
            console.log('element is undefined')
            return null
        }
        viewer = new Cesium.Viewer(element, {
            // 不显示时间线
            timeline: false,
            // 不显示时钟
            animation: false,
            fullscreenButton: false,
            baseLayerPicker: false,
            sceneModePicker: false,
            homeButton: false,
            geocoder: false,
            navigationHelpButton: false,
        })

        addCesiumLocalTile(viewer)

        // addCesiumLocalLabelTile(viewer)

        // load3DModel(viewer)

        // useModelDiffDemo()

        // console.log('viewer======>',viewer);

        viewer._cesiumWidget._creditContainer.style.display = 'none'

        // viewer._creditContainer.children[1].style.display = 'none'

        // viewer.extend(Cesium.viewerCesiumNavigationMixin, {})
        // viewer.extend(Cesium.viewerCesiumInspectorMixin, {})
        // viewer.extend(Cesium.viewerCesium3DTilesInspectorMixin, {})

        // viewer._cesiumWidget._toolbar.style.display = 'none'

        nextTick(() => {
            // addPrimitiveDemo()
        })

        return viewer
    }

    function initScaleBar() {
        const scaleBar = new Cesium.ScaleBar({
            container: 'cesiumContainer',
            // 设置比例尺的最大长度，单位为米
            maxBarLength: 200,
            // 设置比例尺的单位
            units: 'metric',
            // 设置比例尺的位置
            scaleBarContainer: document.getElementById('scaleBarContainer'),
        })
    }

    function initPolygon() {
        const entities = viewer.entities
        let i
        let height
        let positions
        const stripeMaterial = new Cesium.StripeMaterialProperty({
            evenColor: Cesium.Color.WHITE.withAlpha(0.5),
            oddColor: Cesium.Color.BLUE.withAlpha(0.5),
            repeat: 5.0,
        })

        entities.add({
            rectangle: {
                coordinates: Cesium.Rectangle.fromDegrees(
                    -92.0,
                    20.0,
                    -86.0,
                    27.0,
                ),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                stRotation: Cesium.Math.toRadians(45),
                material: stripeMaterial,
            },
        })

        entities.add({
            polygon: {
                hierarchy: new Cesium.PolygonHierarchy(
                    Cesium.Cartesian3.fromDegreesArray([
                        -107.0, 27.0, -107.0, 22.0, -102.0, 23.0, -97.0, 21.0,
                        -97.0, 25.0,
                    ]),
                ),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                material: stripeMaterial,
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-80.0, 25.0),
            ellipse: {
                semiMinorAxis: 300000.0,
                semiMajorAxis: 500000.0,
                rotation: Cesium.Math.toRadians(-40.0),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                stRotation: Cesium.Math.toRadians(22),
                material: stripeMaterial,
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-72.0, 25.0),
            ellipse: {
                semiMinorAxis: 250000.0,
                semiMajorAxis: 250000.0,
                rotation: Cesium.Math.toRadians(-40.0),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                stRotation: Cesium.Math.toRadians(90),
                material: stripeMaterial,
            },
        })

        entities.add({
            rectangle: {
                coordinates: Cesium.Rectangle.fromDegrees(
                    -118.0,
                    38.0,
                    -116.0,
                    40.0,
                ),
                extrudedHeight: 500000.0,
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                stRotation: Cesium.Math.toRadians(45),
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-117.0, 35.0),
            ellipse: {
                semiMinorAxis: 100000.0,
                semiMajorAxis: 200000.0,
                height: 100000.0,
                extrudedHeight: 200000.0,
                rotation: Cesium.Math.toRadians(90.0),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            polygon: {
                hierarchy: new Cesium.PolygonHierarchy(
                    Cesium.Cartesian3.fromDegreesArray([
                        -118.0, 30.0, -115.0, 30.0, -117.1, 31.1, -118.0, 33.0,
                    ]),
                ),
                height: 300000.0,
                extrudedHeight: 700000.0,
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-70.0, 45.0, 100000.0),
            cylinder: {
                hierarchy: new Cesium.PolygonHierarchy(
                    Cesium.Cartesian3.fromDegreesArray([
                        -118.0, 30.0, -115.0, 30.0, -117.1, 31.1, -118.0, 33.0,
                    ]),
                ),
                length: 200000.0,
                topRadius: 150000.0,
                bottomRadius: 150000.0,
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        for (i = 0; i < 5; ++i) {
            height = 100000.0 + 200000.0 * i
            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-106.0, 45.0, height),
                box: {
                    dimensions: new Cesium.Cartesian3(
                        90000.0,
                        90000.0,
                        90000.0,
                    ),
                    outline: true,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    material: Cesium.Color.fromRandom({ alpha: 0.5 }),
                },
            })

            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-102.0, 45.0, height),
                ellipsoid: {
                    radii: new Cesium.Cartesian3(45000.0, 45000.0, 90000.0),
                    outline: true,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    material: Cesium.Color.fromRandom({ alpha: 0.5 }),
                },
            })

            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-98.0, 45.0, height),
                ellipsoid: {
                    radii: new Cesium.Cartesian3(67500.0, 67500.0, 67500.0),
                    outline: true,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                    material: Cesium.Color.fromRandom({ alpha: 0.5 }),
                },
            })
        }

        entities.add({
            wall: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -95.0, 50.0, -85.0, 50.0, -75.0, 50.0,
                ]),
                maximumHeights: [500000, 1000000, 500000],
                minimumHeights: [0, 500000, 0],
                outline: true,
                outlineColor: Cesium.Color.LIGHTGRAY,
                outlineWidth: 4,
                material: Cesium.Color.fromRandom({ alpha: 0.7 }),
            },
        })

        entities.add({
            rectangle: {
                coordinates: Cesium.Rectangle.fromDegrees(
                    -92.0,
                    30.0,
                    -85.0,
                    40.0,
                ),
                material: stripeMaterial,
            },
        })

        entities.add({
            polygon: {
                hierarchy: {
                    holes: [
                        {
                            positions: Cesium.Cartesian3.fromDegreesArray([
                                -107.0, 31.0, -107.0, 39.0, -97.0, 39.0, -97.0,
                                31.0,
                            ]),
                            holes: [
                                {
                                    positions:
                                        Cesium.Cartesian3.fromDegreesArray([
                                            -105.0, 33.0, -99.0, 33.0, -99.0,
                                            37.0, -105.0, 37.0,
                                        ]),
                                    holes: [
                                        {
                                            positions:
                                                Cesium.Cartesian3.fromDegreesArray(
                                                    [
                                                        -103.0, 34.0, -101.0,
                                                        34.0, -101.0, 36.0,
                                                        -103.0, 36.0,
                                                    ],
                                                ),
                                        },
                                    ],
                                },
                            ],
                        },
                    ],
                },
                material: stripeMaterial,
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-80.0, 35.0),
            ellipse: {
                semiMinorAxis: 200000.0,
                semiMajorAxis: 500000.0,
                rotation: Cesium.Math.toRadians(30.0),
                material: stripeMaterial,
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-72.0, 35.0),
            ellipse: {
                semiMinorAxis: 200000.0,
                semiMajorAxis: 200000.0,
                rotation: Cesium.Math.toRadians(30.0),
                material: stripeMaterial,
            },
        })

        entities.add({
            rectangle: {
                coordinates: Cesium.Rectangle.fromDegrees(
                    -110.0,
                    38.0,
                    -107.0,
                    40.0,
                ),
                height: 700000.0,
                extrudedHeight: 1000000.0,
                rotation: Cesium.Math.toRadians(45),
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-110.0, 35.0),
            ellipse: {
                semiMinorAxis: 100000.0,
                semiMajorAxis: 200000.0,
                height: 300000.0,
                extrudedHeight: 700000.0,
                rotation: Cesium.Math.toRadians(-40.0),
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            polygon: {
                hierarchy: new Cesium.PolygonHierarchy(
                    Cesium.Cartesian3.fromDegreesArray([
                        -113.0, 30.0, -110.0, 30.0, -110.0, 33.0, -111.5, 31.0,
                        -113.0, 33.0,
                    ]),
                ),
                extrudedHeight: 300000.0,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            position: Cesium.Cartesian3.fromDegrees(-70.0, 40.0, 200000.0),
            cylinder: {
                hierarchy: new Cesium.PolygonHierarchy(
                    Cesium.Cartesian3.fromDegreesArray([
                        -118.0, 30.0, -115.0, 30.0, -117.1, 31.1, -118.0, 33.0,
                    ]),
                ),
                length: 400000.0,
                topRadius: 0.0,
                bottomRadius: 200000.0,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        for (i = 0; i < 5; ++i) {
            height = 200000.0 * i

            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-65.0, 35.0),
                ellipse: {
                    semiMinorAxis: 200000.0,
                    semiMajorAxis: 200000.0,
                    height: height,
                    material: Cesium.Color.fromRandom({ alpha: 0.5 }),
                },
            })

            entities.add({
                rectangle: {
                    coordinates: Cesium.Rectangle.fromDegrees(
                        -67.0,
                        27.0,
                        -63.0,
                        32.0,
                    ),
                    height: height,
                    material: Cesium.Color.fromRandom({ alpha: 0.5 }),
                },
            })
        }

        for (i = 0; i < 5; ++i) {
            height = 100000.0 + 200000.0 * i
            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-108.0, 45.0, height),
                box: {
                    dimensions: new Cesium.Cartesian3(
                        90000.0,
                        90000.0,
                        90000.0,
                    ),
                    material: Cesium.Color.fromRandom({ alpha: 1.0 }),
                },
            })

            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-104.0, 45.0, height),
                ellipsoid: {
                    radii: new Cesium.Cartesian3(45000.0, 45000.0, 90000.0),
                    material: Cesium.Color.fromRandom({ alpha: 1.0 }),
                },
            })

            entities.add({
                position: Cesium.Cartesian3.fromDegrees(-100.0, 45.0, height),
                ellipsoid: {
                    radii: new Cesium.Cartesian3(67500.0, 67500.0, 67500.0),
                    material: Cesium.Color.fromRandom({ alpha: 1.0 }),
                },
            })
        }

        positions = []
        for (i = 0; i < 40; ++i) {
            positions.push(Cesium.Cartesian3.fromDegrees(-100.0 + i, 15.0))
        }

        entities.add({
            polyline: {
                positions: positions,
                width: 10.0,
                material: new Cesium.PolylineGlowMaterialProperty({
                    color: Cesium.Color.DEEPSKYBLUE,
                    glowPower: 0.25,
                }),
            },
        })

        positions = []
        for (i = 0; i < 40; ++i) {
            positions.push(Cesium.Cartesian3.fromDegrees(-100.0 + i, 9.0))
        }

        entities.add({
            wall: {
                positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                    -90.0, 43.0, 100000.0, -87.5, 45.0, 100000.0, -85.0, 43.0,
                    100000.0, -87.5, 41.0, 100000.0, -90.0, 43.0, 100000.0,
                ]),
                material: new Cesium.CheckerboardMaterialProperty({
                    repeat: new Cesium.Cartesian2(20.0, 6.0),
                }),
            },
        })

        // 红色回旋镖
        entities.add({
            corridor: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -120.0, 45.0, -125.0, 50.0, -125.0, 55.0,
                ]),
                width: 100000,
                material: Cesium.Color.RED,
            },
        })

        entities.add({
            corridor: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -120.0, 45.0, -125.0, 50.0, -125.0, 55.0,
                ]),
                width: 100000,
                height: 300000,
                extrudedHeight: 400000,
                material: Cesium.Color.fromRandom({ alpha: 0.7 }),
            },
        })

        entities.add({
            corridor: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -120.0, 45.0, -125.0, 50.0, -125.0, 55.0,
                ]),
                width: 100000,
                height: 700000,
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 4,
                material: Cesium.Color.fromRandom({ alpha: 0.7 }),
            },
        })

        function starPositions(arms, rOuter, rInner) {
            const angle = Math.PI / arms
            const pos = []
            for (let i = 0; i < 2 * arms; i++) {
                const r = i % 2 === 0 ? rOuter : rInner
                const p = new Cesium.Cartesian2(
                    Math.cos(i * angle) * r,
                    Math.sin(i * angle) * r,
                )
                pos.push(p)
            }
            return pos
        }

        entities.add({
            polylineVolume: {
                positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                    -102.0, 15.0, 100000.0, -105.0, 20.0, 200000.0, -110.0,
                    20.0, 100000.0,
                ]),
                shape: starPositions(7, 30000.0, 20000.0),
                outline: true,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 1,
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        entities.add({
            polylineVolume: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -102.0, 15.0, -105.0, 20.0, -110.0, 20.0,
                ]),
                shape: starPositions(7, 30000.0, 20000.0),
                material: Cesium.Color.fromRandom({ alpha: 1.0 }),
            },
        })

        function computeCircle(radius) {
            const positions = []
            for (let i = 0; i < 360; i++) {
                const radians = Cesium.Math.toRadians(i)
                positions.push(
                    new Cesium.Cartesian2(
                        radius * Math.cos(radians),
                        radius * Math.sin(radians),
                    ),
                )
            }
            return positions
        }

        entities.add({
            polylineVolume: {
                positions: Cesium.Cartesian3.fromDegreesArray([
                    -104.0, 13.0, -107.0, 18.0, -112.0, 18.0,
                ]),
                shape: computeCircle(40000.0),
                material: Cesium.Color.WHITE,
            },
        })
    }
    function initPolygonOverlay(position: [number, number][]) {
        const entities = viewer.entities

        var polygonPositions = [
            Cesium.Cartesian3.fromDegrees(
                -75.62898254394531,
                40.02804946899414,
            ),
            Cesium.Cartesian3.fromDegrees(
                -75.62898254394531,
                40.12804946899414,
            ),
            Cesium.Cartesian3.fromDegrees(
                -75.72898254394531,
                40.12804946899414,
            ),
            Cesium.Cartesian3.fromDegrees(
                -75.72898254394531,
                40.02804946899414,
            ),

            // Cesium.Cartesian3.fromDegrees(-87.5, 45.0),
            // Cesium.Cartesian3.fromDegrees(-90.0, 43.0),
            // Cesium.Cartesian3.fromDegrees(-87.5, 41.0),
            // Cesium.Cartesian3.fromDegrees(-90.0, 43.0),
        ]

        var polygonHierarchy = new Cesium.PolygonHierarchy(polygonPositions, [])

        var polygonGraphics = new Cesium.PolygonGraphics({
            hierarchy: polygonHierarchy,
            material: Cesium.Color.BLUE.withAlpha(0.2),
            // outline: true,
            outlineColor: Cesium.Color.WHEAT,
            outlineWidth: 10,
        })

        entities.add({
            polygon: polygonGraphics,
        })

        viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(
                -75.62898254394531,
                40.07804946899414,
                10000.0,
            ),
        })
        // entities.add({
        //     name: '123',
        //     polygon: {
        //         hierarchy: ,
        //         // positions: [
        //         //     Cesium.Cartesian3.fromDegrees(-87.5, 45.0, 10000.0),
        //         //     Cesium.Cartesian3.fromDegrees(-90.0, 43.0, 10000.0),
        //         //     Cesium.Cartesian3.fromDegrees(-87.5, 41.0, 10000.0),
        //         //     Cesium.Cartesian3.fromDegrees(-90.0, 43.0, 100.0),
        //         // ],

        //         // -85.0, 43.0, 10000.0,

        //         material: new Cesium.CheckerboardMaterialProperty({
        //             repeat: new Cesium.Cartesian2(20.0, 6.0),
        //         }),
        //     },
        // })
    }

    interface Polygon {
        coordinates: []
    }

    function addPolygonOverlay(postions: number[][], id?: string) {
        let polygonPositions: Cesium.Cartesian3[] = []

        polygonPositions = postions.map((pos) => {
            return Cesium.Cartesian3.fromDegrees(pos[0], pos[1])
        })

        const polygonHierarchy = new Cesium.PolygonHierarchy(
            polygonPositions,
            [],
        )

        const polygonGraphics = new Cesium.PolygonGraphics({
            hierarchy: polygonHierarchy,
            material: Cesium.Color.ORANGE.withAlpha(0.2),
            outlineColor: Cesium.Color.WHITE.withAlpha(0.4),
            outlineWidth: 20,

            height: 0,
            outline: true,
        })

        const params: Cesium.Entity.ConstructorOptions = id
            ? {
                id,
                polygon: polygonGraphics,
            }
            : { polygon: polygonGraphics }

        const ply = viewer.entities.add(params)

        return ply
    }

    function addTexturedPolygon(postions: number[][], id?: string) {
        viewer.entities.add({
            name: 'Extruded textured polygon with per-position heights and custom texture coordinates',
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights([
                    -118.4, 40.4, 0, -118.4, 37, 0, -114.2, 37.0, 0, -108.0, 37,
                    0, -108.0, 40.4, 0,
                ]),
                // textureCoordinates: {
                //     positions: [
                //         new Cesium.Cartesian2(0, 1),
                //         new Cesium.Cartesian2(0, 0),
                //         new Cesium.Cartesian2(0.5, 0),
                //         new Cesium.Cartesian2(1, 0),
                //         new Cesium.Cartesian2(1, 1),
                //     ],
                // },
                outlineColor: Cesium.Color.WHITE.withAlpha(0.4),
                outlineWidth: 40,
                height: 0,
                perPositionHeight: true,
                extrudedHeight: 0,
                outline: true,
                material: '/img/下载.png',
            },
        })
    }


    function initPolygonOutInEvent() {
        const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)

        // 鼠标移入事件
        handler.setInputAction(function (movement) {
            const pickedObject = viewer.scene.pick(movement.endPosition)
            if (
                Cesium.defined(pickedObject) &&
                pickedObject.id === polygonEntity
            ) {

                // 鼠标移入多边形时加载图片
                var imageEntity = viewer.entities.add({
                    position: Cesium.Cartesian3.fromDegrees(lon, lat),
                    billboard: {
                        image: 'path_to_image.png',
                        // 可选的属性，如缩放、颜色等
                    },
                })
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

        // 监听鼠标移出事件
        handler.setInputAction(function (movement) {
            var pickedObject = viewer.scene.pick(movement.endPosition)
            if (
                Cesium.defined(pickedObject) &&
                pickedObject.id === polygonEntity
            ) {
                // 鼠标移出多边形时清除图片
                viewer.entities.remove(imageEntity)
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }

    function focusPolygonById(id: string) {
        const entities = viewer.entities.values

        // 遍历实体，查找指定 ID 的多边形
        for (let i = 0; i < entities.length; i++) {
            const entity = entities[i]
            if (entity.polygon && entity.id === id) {
                console.log('entity======>', entity)

                // 判断是否为多边形实体，并且 ID 是否匹配
                const polygon = entity.polygon
                const polygonHierarchy = polygon.hierarchy
                // viewer.camera.flyToBoundingSphere(boundingSphere) // 将相机飞到多边形的包围球

                // const center = Cesium.BoundingSphere.fromPoints(
                //     polygonHierarchy!.getValue().positions,
                // ).center

                viewer.flyTo(entity, {
                    duration: 2, // 飞行时间为2秒
                    maximumHeight: 1000000000, // 相机最大高度为1000米
                    // 相机的俯仰角
                    offset: new Cesium.HeadingPitchRange(
                        0,
                        Cesium.Math.toRadians(-90),
                    ),
                })

                break
            }
        }
    }

    /**
     * @description 鼠标移动到多边形上让其高亮
     */
    function makePolygonHoverHighlight(viewer: Cesium.Viewer) {
        // 监听鼠标移动事件
        const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
        handler.setInputAction(function (movement: any) {
            const pickedObject = viewer.scene.pick(movement.endPosition)

            if (!pickedObject) return

            const polygon = pickedObject.id as Cesium.Entity

            if (
                Cesium.defined(pickedObject)
                // && pickedObject.id === polygon
            ) {
                // 鼠标移动到多边形上，修改样式为高亮状态
                // polygon.polygon.material = Cesium.Color.YELLOW.withAlpha(0.5)

                if (!polygon) return

                polygon.polygon!.material = Cesium.Color.YELLOW.withAlpha(0.8)
            } else {
                // 鼠标离开多边形，恢复原样式
                polygon.polygon!.material = Cesium.Color.RED.withAlpha(0.5)
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }

    let pin_builder = new Cesium.PinBuilder()

    function initCustomDataSource() {
        entityDataSource = new Cesium.CustomDataSource('entity-datasource')
        return entityDataSource
    }

    // 添加静态图标到指定位置

    // TODO: 增加icon 图标
    function addStaticIcon(entity_info: {
        loc: number[]
        icon: string
        id: string
        name: string
        color?: Cesium.Color
    }): Promise<{ entity: Cesium.Entity; color: Cesium.Color }> | null {
        if (entity_info.loc.length < 2) {
            console.log('entity.loc 不符合格式', entity_info.loc)
            return null
        }

        const color = entity_info.color || Cesium.Color.fromRandom({ alpha: 1 })

        entity_info.icon = entity_info.icon || iconList.Crosshair

        const entity_promise = new Promise<{
            entity: Cesium.Entity
            color: Cesium.Color
        }>((resolve, reject) => {
            const canvas_promise = pin_builder.fromUrl(
                entity_info.icon,
                // iconList.Crosshair,
                color,
                48,
            )

            if (canvas_promise instanceof Promise) {
                canvas_promise.then((canvas: HTMLCanvasElement) => {
                    let entity = new Cesium.Entity({
                        id: entity_info.id || uuidv4(),
                        position: Cesium.Cartesian3.fromDegrees(
                            entity_info.loc[0],
                            entity_info.loc[1],
                            // 100000,
                        ),
                        billboard: {
                            image: canvas,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            color: Cesium.Color.WHITE,
                            scale: 0.83,
                            alignedAxis: Cesium.Cartesian3.ZERO, // default
                            // disableDepthTestDistance:1,
                        },
                        // point: {
                        // 	// color: Color.BLACK,
                        // 	// pixelSize: 5,
                        // 	heightReference: HeightReference.clampToGround
                        // },
                        label: {
                            //填充色
                            fillColor: Cesium.Color.WHITE,
                            //字体
                            font: 'bold 8pt Segoe UI Semibold',
                            // // 水平原点
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            // // 边框颜色
                            // outlineColor: {
                            // 	rgba: [0, 0, 0, 255],
                            // },
                            outlineColor: Cesium.Color.BLACK,
                            outlineWidth: 3,
                            // clamp: true,
                            // //相对于当前点的字符坐标偏离
                            // pixelOffset: {
                            // 	cartesian2: [
                            // 		// -15,
                            // 		// -50,
                            // 		0, -55,
                            // 	],
                            // },
                            pixelOffset: new Cesium.Cartesian2(0, -65),
                            // 缩放
                            // scale: 1,
                            // 是否显示
                            // show: true,
                            // 样式
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            // 文字内容
                            text: entity_info.name,
                            // 垂直原点
                            verticalOrigin: Cesium.VerticalOrigin.TOP,
                            // eyeOffset: {
                            // 	cartesian: [0, 0, -10],
                            // },
                            // FIXED: #495 fixed 放大缩小地图，图标标题会看不到 http://prj.jingcao.xyz/issues/495
                            // eyeOffset: new Cartesian3(0, 0, -100000),
                        },
                    })
                    if (entityDataSource) {
                        entity = entityDataSource.entities.add(entity)
                        resolve({
                            entity,
                            color: color.clone(),
                        })
                    } else {
                        entityDataSource = initCustomDataSource()

                        viewer.dataSources.add(entityDataSource)

                        entityDataSource.entities.add(entity)

                        resolve({
                            entity,
                            color: color.clone(),
                        })

                        console.warn('entityDataSource is null')
                    }
                })
            } else {
                const canvas = canvas_promise

                let entity = new Cesium.Entity({
                    id: entity_info.id || uuidv4(),
                    position: Cesium.Cartesian3.fromDegrees(
                        entity_info.loc[0],
                        entity_info.loc[1],
                        // 100000,
                    ),
                    billboard: {
                        image: canvas,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        color: Cesium.Color.WHITE,
                        scale: 0.83,
                        alignedAxis: Cesium.Cartesian3.ZERO, // default
                        // disableDepthTestDistance:1,
                    },
                    // point: {
                    // 	// color: Color.BLACK,
                    // 	// pixelSize: 5,
                    // 	heightReference: HeightReference.clampToGround
                    // },
                    label: {
                        //填充色
                        fillColor: Cesium.Color.WHITE,
                        //字体
                        font: 'bold 8pt Segoe UI Semibold',
                        // // 水平原点
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        // // 边框颜色
                        // outlineColor: {
                        // 	rgba: [0, 0, 0, 255],
                        // },
                        outlineColor: Cesium.Color.BLACK,
                        outlineWidth: 3,
                        // clamp: true,
                        // //相对于当前点的字符坐标偏离
                        // pixelOffset: {
                        // 	cartesian2: [
                        // 		// -15,
                        // 		// -50,
                        // 		0, -55,
                        // 	],
                        // },
                        pixelOffset: new Cesium.Cartesian2(0, -65),
                        // 缩放
                        // scale: 1,
                        // 是否显示
                        // show: true,
                        // 样式
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        // 文字内容
                        text: entity_info.name,
                        // 垂直原点
                        verticalOrigin: Cesium.VerticalOrigin.TOP,
                        // eyeOffset: {
                        // 	cartesian: [0, 0, -10],
                        // },
                        // FIXED: #495 fixed 放大缩小地图，图标标题会看不到 http://prj.jingcao.xyz/issues/495
                        // eyeOffset: new Cartesian3(0, 0, -100000),
                    },
                })
                if (entityDataSource) {
                    entity = entityDataSource.entities.add(entity)
                    resolve({
                        entity,
                        color: color.clone(),
                    })
                } else {
                    entityDataSource = initCustomDataSource()

                    viewer.dataSources.add(entityDataSource)

                    entityDataSource.entities.add(entity)

                    resolve({
                        entity,
                        color: color.clone(),
                    })

                    console.warn('entityDataSource is null')
                }
            }
        })

        return entity_promise
    }

    function initEarthViewer() {
        viewer = (window.viewer as unknown as Cesium.Viewer)!
        pin_builder = new Cesium.PinBuilder()
        return viewer
    }

    return {
        useModelDiffDemo,
        initCesium,
        useDynamicArea,
        useDynamicPath,
        addCesiumLocalTile,
        addCesiumLocalLabelTile,
        initPolygon,
        initPolygonOverlay,
        addPolygonOverlay,
        makePolygonHoverHighlight,
        focusPolygonById,
        addStaticIcon,
        setViewer,
        setEntityDataSource,
        initEarthViewer,
        initCustomDataSource,
        addTexturedPolygon,
    }
}

export default useCesium
